package com.mxx.bu_yang.activity.on_line;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.utils.MapUrlParamsUtils;
import com.mxx.basic.utils.SPUtils;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.ScannerService;
import com.mxx.bu_yang.activity.LoginActivity;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.GoodsOwnerListDialog;
import com.mxx.bu_yang.dialog.ScanSuccessDialog;
import com.mxx.bu_yang.response.MaterialCodeResponse;
import com.mxx.bu_yang.response.StockDetailResponse;
import com.mxx.common.config.ConstantsConfig;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.observer.DefaultModelObserver;


import java.util.HashMap;
import java.util.Map;

/**
 * 作者：刘江飞
 * 时间：2020/10/14  16:25
 * 邮箱：642371742Z@qq.com
 * 描述：
 **/
public class GoodsManagerActivity extends CommonTitleActivity {
    private TextView tv_cancel;
    private TextView tv_query;
    private TextView tv_warehouse;
    private TextView tv_goods_owner;
    private TextView tv_scan_value;
    private final Map<String, Object> paramsMap = new HashMap<>();
    private int tv_goods_owner_height;
    private int tv_goods_owner_width;
    private EditText edt_result;
    private ScanReceiver receiver;
    private TextWatcher textWatcher;

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_NONE;
    }

    /**
     * 获取当前页面的布局文件
     *
     * @return int
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_goods_manager;
    }

    @Override
    public void initView() {
        super.initView();
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_query = findViewById(R.id.tv_query);
        tv_warehouse = findViewById(R.id.tv_warehouse);
        tv_goods_owner = findViewById(R.id.tv_goods_owner);
        tv_scan_value = findViewById(R.id.tv_scan_value);
        edt_result = findViewById(R.id.edt_result);
        tv_goods_owner.post(() -> tv_goods_owner_height = tv_goods_owner.getHeight());
        tv_goods_owner.post(() -> tv_goods_owner_width = tv_goods_owner.getWidth());

        tv_title.setText("货品管理");
        startMyService();
        initReceiver();
        initTextWatcher();
        setWareHouseInfo();
    }

    private void startMyService() {
        Intent intent = new Intent(this, ScannerService.class);
        startService(intent);
    }

    private void initReceiver() {
        receiver = new ScanReceiver();
        IntentFilter filter = new IntentFilter(ScannerService.ACTION);
        registerReceiver(receiver, filter);
    }

    private void initTextWatcher() {
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.i("TAG", s.toString());
            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                Log.i("TAG", s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                String barcode = s.toString();
                paramsMap.put("barcode", barcode);
                resetEditText();
                runOnUiThread(() -> showScanSuccessDialog());
            }
        };

    }

    private void resetEditText() {
        edt_result.removeTextChangedListener(textWatcher);
        edt_result.setText("");
        edt_result.addTextChangedListener(textWatcher);
    }

    private void showScanSuccessDialog() {
        ScanSuccessDialog successDialog = new ScanSuccessDialog();
        successDialog.setDialogDismissListener(dialog -> loadMaterialInfo());
        successDialog.show(getSupportFragmentManager(), "ScanSuccessDialog");
    }

    private void loadMaterialInfo() {
        String barcode = (String) paramsMap.get("barcode");
        Map<String, String> request_params = new HashMap<>();
        request_params.put("barcode", barcode);
        String json = "?" + MapUrlParamsUtils.getUrlParamsByMap(request_params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationMateriel/getMaterielNumber" + json)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new DefaultModelObserver(true, this) {
                    @Override
                    protected void handlerJsonObjectData(String objectJson) {
                        MaterialCodeResponse response = paramsObjectJsonToObject(objectJson);
                        loadMaterialInfo(response);
                    }
                });
    }


    private MaterialCodeResponse paramsObjectJsonToObject(String objectJson) {
        MaterialCodeResponse response = new MaterialCodeResponse();
        if (objectJson != null && !objectJson.isEmpty()) {
            response = new Gson().fromJson(objectJson, new TypeToken<MaterialCodeResponse>() {
            }.getType());
        }
        return response;
    }

    private void loadMaterialInfo(MaterialCodeResponse response) {
        if (response == null) {
            return;
        }
        String lotNo = response.lotNo;
        paramsMap.put("lotNo", lotNo);
        String materialNo = response.materialNo;
        tv_scan_value.setText(materialNo);
        paramsMap.put("materielNumber", materialNo);
    }

    private void setWareHouseInfo() {
        String ware_name = getWareName();
        if (ware_name == null || ware_name.isEmpty()) {
            return;
        }
        tv_warehouse.setText(ware_name);

        paramsMap.put("wareId", getWareId());
    }

    @Override
    public void initListener() {
        super.initListener();
        tv_cancel.setOnClickListener(this);
        tv_query.setOnClickListener(this);
        tv_warehouse.setOnClickListener(this);
        tv_goods_owner.setOnClickListener(this);
        edt_result.addTextChangedListener(textWatcher);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_cancel) {
            finish();
        }
        if (view.getId() == R.id.tv_query) {
            check();
        }
        if (view.getId() == R.id.tv_goods_owner) {
            showSelectOwnerDialog();
        }
    }

    private void check() {
        String ware_house = tv_warehouse.getText().toString();
//        String owner = tv_goods_owner.getText().toString();
        String goods_name = tv_scan_value.getText().toString();
        if (ware_house.isEmpty()) {
            String hint = "请选择仓库";
            ToastUtils.showToast(this, hint);
            return;
        }
        if (goods_name.isEmpty()) {
            String hint = "请扫码获取货品信息";
            ToastUtils.showToast(this, hint);
            return;
        }
        query();
    }


    private void query() {
        String lotNo = (String) paramsMap.get("lotNo");
        String materielNumber = (String) paramsMap.get("materielNumber");
        if (lotNo == null || lotNo.isEmpty()
                || materielNumber == null || materielNumber.isEmpty()) {
            ToastUtils.showToast(this, "请先扫码获取商品编码");
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("wareId", String.valueOf(getWareId()));
        params.put("lotNo", lotNo);
        params.put("materielNumber", materielNumber);
        String json = "?" + MapUrlParamsUtils.getUrlParamsByMap(params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationMateriel/selMaterielStockDetail" + json)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new DefaultModelObserver(true, this) {
                    @Override
                    protected void handlerJsonObjectData(String objectJson) {
                        skipToStockDetail(objectJson, lotNo);
                    }
                });
    }

    private void switchToLogin() {
        ToastUtils.showToast(this, "IP为空，请到登录页重新设置IP");
        SPUtils.put(this, "login_info", "");
        Intent mIntent = new Intent(this, LoginActivity.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mIntent);
        finish();
    }

    private void skipToStockDetail(String objectJson, String lot_no) {
        if (objectJson == null || objectJson.isEmpty()) {
            ToastUtils.showToast(this, "物料详情为空");
            return;
        }
        StockDetailResponse response = new Gson().fromJson(objectJson, new TypeToken<StockDetailResponse>() {
        }.getType());
        if (response != null) {
            response.lot_no = lot_no;
        }

        Intent mIntent = new Intent(this, StockDetailActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(ConstantsConfig.VALUE, new Gson().toJson(response));
        mIntent.putExtras(mBundle);
        startActivityForResult(mIntent, 1004);
    }

    private void showSelectOwnerDialog() {
        int[] location = new int[2];
        tv_goods_owner.getLocationOnScreen(location);
        tv_goods_owner.getLocationOnScreen(location);
        GoodsOwnerListDialog dialog = new GoodsOwnerListDialog(tv_goods_owner_width, location[0]
                , tv_goods_owner_height, location[1], false);

        Bundle mBundle = new Bundle();

        dialog.setArguments(mBundle);
        dialog.setBackDataListener(response -> tv_goods_owner.setText(response.name));
        dialog.show(this.getSupportFragmentManager()
                , "BaseDialog");
    }

    public class ScanReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            edt_result.append(bundle.getString(ScannerService.BAR_CODE));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
